const WebSocket = require('ws');
const fs = require('fs');
const url = require('url');
const { exec,execSync } = require('child_process');
// 创建WebSocket服务器实例，监听端口3000
const wss = new WebSocket.Server({ port: 3002 });
 
wss.on('connection', function connection(ws,req) {
  // 当客户端连接时触发
  var info=url.parse(req.url,true);
  var p='./tmpdata'+decodeURIComponent(info.pathname);
  var readysize= info.query['size'];
  //,JSON.stringify(info)
  console.log("准备文件大小",readysize);
    if(fs.existsSync(p))fs.unlinkSync(p);
    ws.on('message', function incoming(message) {
        console.log("收到消息"+p+",大小 "+((message.length/1024/1024)+"M"))
        // 当服务器接收到客户端发来的消息时触发
        //console.log('received: %s', message);
        // 创建一个可写入流
        const writeStream = fs.createWriteStream(p, {
        flags: 'a' // 使用 'a' 标志以追加模式写入文件
        });
        
        // 写入数据到文件末尾
        writeStream.write(message, 'utf8', () => {
        //console.log('数据已追加到文件');
        // 关闭可写入流
        writeStream.end();
        
        var size=fs.statSync(p).size;
        console.log((size/1024/1024)+"M");
        

        if(size==readysize){
          ws.send("done");
          res=execSync('curl -X POST -s -F "file=@'+p+'" "http://127.0.0.1:3000/share/file/"')
          ws.send(res.toString())
          if(fs.existsSync(p))fs.unlinkSync(p);
        }else{
          ws.send(JSON.stringify({size:size,readysize:readysize}));
        }
        
        

        //模拟http post上传文件请求
        
        });
        delete message;
    });
 
  // 发送消息给客户端
  ws.send('something');
});
 
console.log('WebSocket server is running on ws://localhost:3000');
